<template>
	<view class="content" style="background-color: #F4F4F4;height: 100vh;">
		<tn-nav-bar bgClass="bg-gradual-blue">
			<view>
				{{ bleName }}
			</view>
		</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="margin-sm">
				<view class="margin-tb-sm">
					<tn-list-cell hover radius @click="showKeyboard('SJSOC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">电池包设计容量</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['SJSOC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> AH</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover radius @click="showKeyboard('TOV')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">总压过压保护</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['TOV']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> V</text>
							</view>
						</view>
					</tn-list-cell>
				</view>

				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('TOVR')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">总压过放保护</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['TOVR']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> V</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电高温保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTCDelay')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电高温保护恢复温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTCDelay']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTC')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电低温保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTC']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTCDelay')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">充电低温保护恢复温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTCDelay']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTD')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温放电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTD']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('OTDDelay')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">高温放电保护恢复温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['OTDDelay']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTD')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温放电保护温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTD']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="margin-tb-sm">
					<tn-list-cell hover @click="showKeyboard('UTDDelay')">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">低温放电保护恢复温度</view>
							</view>
							<view class="list__right">
								<text class="text-lg ">{{readValue['UTDDelay']}}</text>
								<text class=" tn-flex-1 padding-left-sm"> ℃</text>
							</view>
						</view>
					</tn-list-cell>
				</view>
			</view>


			<view style="height: 10vh;"></view>
			<tn-modal :value="showKey" @click="setBleVal" @cancel="onDialogClose" custom :button="buttons"
				padding='30rpx'>
				<view class="custom-modal-content">
					<tn-form :labelWidth="140" style="width: 100%;">
						<tn-form-item :borderBottom="false">
							<tn-input v-model="inputValue" border type="number"></tn-input>
						</tn-form-item>
					</tn-form>
				</view>
			</tn-modal>



		</view>
	</view>
</template>

<script>
	import BLE from "@/libs/bluetooth/BLE.js";
	import Protocol from "@/libs/protocol/chaoliyuan/protocol.js";
	import BLE_DATA from "@/libs/protocol/chaoliyuan/bleData.js";

	const TAG = '0000000000000000000000000000000000000000'
	//查询所有参数指令
	const CMD = '010300000076C42C'

	let timer = null;
	let sendTimer = null;
	let isConnectTimer = null;
	export default {
		data() {
			return {
				bleName: '',
				inputValue: '',
				showKey: false,
				isFirst: true,
				isWrite: false,
				readIndex: 0,
				activeItem: {},
				buttons: [{
						text: '取消',
						backgroundColor: '#AAAAAA',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#01BEFF',
						fontColor: '#FFFFFF'
					}
				],
				readAllParams: bleParams,
				readValue: {},
				sendCmd: CMD,
				resData: '',
				lenValue: 0,
				nValue: 0,
				xValue: 0,
			}
		},

		onLoad(options) {
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			if (options.n) {
				this.bleName = options.n
			}
			var that = this;
			let readValue = {}
			for (var i = 0; i < that.readAllParams.length; i++) {
				let t = that.readAllParams[i]
				if (t.type === 2) {
					readValue[t.name[0]] = ''
					readValue[t.name[1]] = ''
				} else {
					readValue[t.name] = ''
				}
			}
			this.readValue = JSON.parse(JSON.stringify(readValue))
			//设置值更改函数
			that.SetValueChanged();
		},
		onShow() {
			let that = this
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			const state = getApp().globalData.bleObj.state
			if (state) {
				that.isFirst = true
				that.sendFirst(this)
				timer = setInterval(() => {
					that.sendFirst(this)
				}, 2000)
			} else {
				console.log('开始连接蓝牙');
				BLE.Connect(getApp().globalData.bleObj.deviceId, () => {
					console.log('连接成功');
					timer = setInterval(() => {
						that.sendFirst(this)
					}, 2000)
				})
			}
		},
		onHide() {
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			this.resData = ''
			this.readIndex = 0;
		},
		methods: {
			setBleVal(e) {
				if (e.index < 1) {
					this.showKey = false
					this.inputValue = ''
					return
				}
				this.$tn.message.toast('下发中')
				let that = this
				let allItems = this.readAllParams
				let allItemsMap = {};
				for (var i = 0; i < allItems.length; i++) {
					let t = allItems[i]
					if (t.type === 2) {
						allItemsMap[t.name[0]] = {
							...t,
							value: (t.value && t.value[0]) ? t.value[0] : ''
						}
						allItemsMap[t.name[1]] = {
							...t,
							value: (t.value && t.value[1]) ? t.value[1] : ''
						}
					} else {
						allItemsMap[t.name] = t
					}
				}
				console.log('allItemsMap', allItemsMap);
				let params = allItemsMap[this.activeItem]
				console.log('params', params);
				let v = parseFloat(this.inputValue);
				if (!isNaN(v)) {
					console.log('v', v);
					let hex = ''
					if (params.type === 2) {
						let name0Val = allItemsMap[params.name[0]].value
						let name1Val = allItemsMap[params.name[1]].value
						if (that.activeItem === params.name[0]) {
							name0Val = v
						} else {
							name1Val = v
						}
						switch (params.start) {
							case '004B':
								name0Val = name0Val - 30
								name1Val = name1Val - 30
								break;
							case '004C':
								name0Val = name0Val + 40
								name1Val = name1Val + 40
								break;
							case '004D':
								name0Val = name0Val - 30
								name1Val = name1Val - 30
								break;
							case '004E':
								name0Val = name0Val + 40
								name1Val = name1Val + 40
								break;
						}
						hex = name0Val.toString(16).padStart(2, '0').toUpperCase() + "" + name1Val
							.toString(16).padStart(2, '0').toUpperCase()
					}

					if (params.type === 0) {
						switch (params.start) {
							case '0054':
							case '0056':
							case '0061':
							case '0062': //总压过压保护、总压过放保护
								hex = (v * 100).toString(16).padStart(params.len * 2, '0')
								break;
							case '000E': //设置电池容量
								hex = (v * 1000).toString(16).padStart(8, '0') +
									(allItemsMap['FCC'].value * 1000).toString(16).padStart(8, '0') +
									(allItemsMap['RC'].value * 1000).toString(16).padStart(8, '0');
								params.len = 12
								break;
						}
					}
					console.log('hex', hex);
					let cmd = Protocol.buildWriteCmd(params, that.nValue, that.xValue, hex)
					that.isWrite = true;
					setTimeout(() => {
						that.isWrite = false;
						this.$tn.message.closeLoading()
						Protocol.sendCommand(cmd, async () => {
							that.readValue[that.activeItem] = that.inputValue
							that.showKey = false
							this.$tn.message.toast('指令下发成功')
						})
					}, 2000)
				}
			},
			onDialogClose() {
				this.showKey = false;
			},
			showKeyboard(item) {
				this.activeItem = item;
				this.showKey = true
				this.inputValue = this.readValue[item]
			},
			sendFirst(that) {
				if (!that) {
					that = this
				}
				if (that.isFirst && !that.isWrite) {
					that.isFirst = false
					that.resData = ''
					Protocol.sendCommand(that.sendCmd, () => {})
				}
			},
			//设置蓝牙请求数据
			SetValueChanged() {
				var that = this;
				//处理数据
				BLE.bleCallBack.CharacteristicValueChange = function(res) {
					if (res != undefined && res != null && res != '') {
						if (res === TAG) {
							that.resData = ''
							that.isFirst = true
						} else {
							//console.log('that.resData ', that.resData);
							that.resData = that.resData + res.toUpperCase();
							if (that.resData.startsWith('0110') || res.startsWith('0110')) {
								console.log('that.resData', that.resData);
								that.isFirst = true
								that.isWrite = false;
								that.resData = ''
							} else if (that.resData.startsWith('0103')) {
								that.isFirst = true
								let crcStr = that.resData.substr(that.resData.length - 4, that.resData.length)
								let str = that.resData.substr(0, that.resData.length - 4)
								const crc = Protocol.crc16Modbus(str).toUpperCase();
								if (crc === crcStr) {
									if (that.sendCmd === CMD) {
										that.lenValue = that.resData.substr(4, 2)
										that.nValue = that.resData.substr(6, 4)
										that.xValue = that.resData.substr(10, 4)
										let result = that.resData;
										Protocol.solutionData(result, that.readAllParams, that.nValue, that.xValue,
											that.sendCmd)
										that.readAllParams.map(t => {
											if (t.type === 2) {
												if (t.value && t.value[1]) {
													that.readValue[t.name[0]] = t.value[0]
													that.readValue[t.name[1]] = t.value[1]
												} else {
													that.readValue[t.name[0]] = ''
													that.readValue[t.name[1]] = ''
												}
											} else {
												that.readValue[t.name] = t.value
											}

										})
										that.sendCmd = ''
										let startTen = parseInt('005C', 16) + parseInt(that.nValue, 16) + parseInt(that
											.xValue, 16)
										let tCmd = '0103' + startTen.toString(16).padStart(4, '0').toUpperCase() +
											'001F'
										that.sendCmd = tCmd + Protocol.crc16Modbus(tCmd)
										Protocol.sendCommand(that.sendCmd, () => {
											//console.log("发送------");
										})
									} else {
										let result = that.resData;
										Protocol.solutionData(result, that.readAllParams, that.nValue, that.xValue,
											that.sendCmd)
										that.readAllParams.map(t => {
											if (t.type === 2) {
												if (t.value && t.value[1]) {
													that.readValue[t.name[0]] = t.value[0]
													that.readValue[t.name[1]] = t.value[1]
												} else {
													that.readValue[t.name[0]] = ''
													that.readValue[t.name[1]] = ''
												}
											} else {
												that.readValue[t.name] = t.value
											}
										})
										that.sendCmd = CMD
										that.resData = ''
									}
									that.resData = ''
								}
							} else {
								that.resData = ''
								that.isFirst = true
							}
						}
					}
				}
			},
		}
	}

	const bleParams = [{
			start: '000E',
			isN: true,
			isX: true,
			len: 4,
			type: 0,
			name: 'SJSOC',
			text: '电池包设计容量'
		},
		{
			start: '0010',
			isN: true,
			isX: true,
			len: 4,
			type: 0,
			name: 'FCC',
			text: '当前电池满容量'
		},
		{
			start: '0012',
			isN: true,
			isX: true,
			len: 4,
			type: 0,
			name: 'RC',
			text: '电池剩余容量'
		}, {
			start: '0045',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['Protect_OCC', 'Protect_OCCDelay'],
			text: '充电过流保护'
		},
		{
			start: '0046',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['Protect_OV', 'Protect_OVDelay'],
			text: '电芯过压保护'
		},
		{
			start: '004B',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['OTD', 'OTDDelay'],
			text: '高温放电保护温度、高温放电保护延时'
		},
		{
			start: '004C',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['UTD', 'UTDDelay'],
			text: '低温放电保护温度、低温放电保护延时'
		},
		{
			start: '004D',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['OTC', 'OTCDelay'],
			text: '高温充电保护温度、高温充电保护延时'
		},
		{
			start: '004E',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['UTC', 'UTCDelay'],
			text: '低温充电保护温度、低温充电保护延时'
		},
		{
			start: '004F',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['Vdiff', 'VdiffDelay'],
			text: '均衡开启电压、低温充电保护延时'
		},
		{
			start: '0052',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['ProtectMTemp', 'ProtectMTempDelay'],
			text: '环境高温保护、恢复'
		},
		{
			start: '0053',
			isN: true,
			isX: true,
			len: 2,
			type: 2,
			name: ['ProtectNTemp', 'ProtectNTempDelay'],
			text: '环境低温保护、恢复'
		},
		{
			start: '0054',
			isN: true,
			isX: true,
			len: 2,
			type: 0,
			name: 'TOV',
			text: '总压过压保护'
		},
		{
			start: '0056',
			isN: true,
			isX: true,
			len: 2,
			type: 0,
			name: 'TOVR',
			text: '总压过放保护'
		}
	]
</script>


<style lang="scss" scoped>
	.list {
		&__left {
			display: flex;
			align-items: center;
			justify-content: flex-start;

			&__icon,
			&__image {
				margin-right: 18rpx;
			}
		}

		&__right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}

	.list-icon-text,
	.list-image-text {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.list-image-text {
		.list {
			&__left {
				&__image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
</style>